package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.amqp.IotMsgNotifyData;
import com.zzyl.nursing.vo.amqp.IotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DeviceDataServiceImpl  extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {

@Autowired
private DeviceServiceImpl deviceService;
@Autowired
private RedisTemplate redisTemplate;


    @Override
    public void saveDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        log.info("开始保存设备数据");
        try {
            //1.解析设备上报数据值
            String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
            Device device = deviceService.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
            if (device==null){
                log.error("设备不存在",deviceId);
                return;
            }
            //解析设备上报数据值
            List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
            ArrayList<DeviceData> deviceDataList = new ArrayList<>();
            for (IotMsgService service : services) {
                String eventTime = service.getEventTime();
                LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
                //时区转换
                LocalDateTime beijTime = localDateTime.atZone(ZoneId.of("UTC"))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
                Map<String, Object> properties = service.getProperties();
                properties.forEach((k,v)->{
                    DeviceData deviceData = new DeviceData();
                    BeanUtils.copyProperties(device,deviceData);
                    //处理ID
                    deviceData.setId(null);
                    deviceData.setFunctionId( k);
                    deviceData.setDataValue(v.toString());
                    deviceData.setAlarmTime(beijTime);
                    deviceDataList.add(deviceData);
                });
            }
            super.saveBatch(deviceDataList);
            redisTemplate.opsForHash().put("deviceData",deviceId, JSONUtil.toJsonStr(deviceDataList));
        } catch (Exception e) {
            log.error("保存设备数据异常",e);
        }
    }





    /**
     * 查询设备数据列表
     *
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto){

        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        Page<DeviceData> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        //模糊查询设备名称
        if(StringUtils.isNotEmpty(dto.getDeviceName())){
            lambdaQueryWrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        //精确查询功能名称
        if (StringUtils.isNotEmpty(dto.getFunctionId())) {
            lambdaQueryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        //时间范围查询
        if(ObjectUtils.isNotEmpty(dto.getStartTime()) && ObjectUtils.isNotEmpty(dto.getEndTime())){
            lambdaQueryWrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }

        //分页查询
        page = page(page,lambdaQueryWrapper);

        //封装分页对象
        return getTableDataInfo(page);

    }

    /**
     * 封装分页对象
     * @param page
     * @return
     */
    @NotNull
    private static TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }
}
